<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/interface' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>商品列表</el-breadcrumb-item> -->
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="温馨提示：只允许设置三级分类参数信息！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-form>
        <el-form-item label="选择商品分类">
          <el-cascader
            v-model="value"
            :options="options"
            :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtn"
            size="mini"
            @click="dialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table
            height="280"
            style="margin-top: 20px"
            :data="tableData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column header-align="center" align="center" type="expand">
              <!-- 循环tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  >{{ item }}</el-tag
                >
                <!-- 控制input和button显示与隐藏 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column header-align="center" align="center" type="index">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showExid(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeId(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数 -->
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="dialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table
            height="280"
            style="margin-top: 20px"
            :data="tableData1"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column header-align="center" align="center" type="expand">
            </el-table-column>
            <!-- 索引 -->
            <el-table-column header-align="center" align="center" type="index">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showExid(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeId(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + dialogText"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      show-close
      @close="addDialog"
    >
      <el-form
        :model="numberValidateForm"
        ref="numberValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="this.dialogText"
          prop="attr_name"
          :rules="[{ required: true, message: this.dialogText + '不能为空' }]"
        >
          <el-input
            type="txt"
            v-model="numberValidateForm.attr_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManyArgument">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + dialogText"
      :visible.sync="exitArgument"
      width="50%"
      :before-close="handleClose"
      show-close
      @close="exitDialog"
    >
      <el-form
        :model="exitValidateForm"
        ref="numberValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="this.dialogText"
          prop="attr_name"
          :rules="[{ required: true, message: this.dialogText + '不能为空' }]"
        >
          <el-input
            type="txt"
            v-model="exitValidateForm.attr_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exitArgument = false">取 消</el-button>
        <el-button type="primary" @click="exitManyArgument">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //级联选择器
      options: [],
      //级联选择器的选中触发的值
      value: [],
      //默认选中
      activeName: "many",
      //获取的值
      sMany: [],
      sOnly: [],
      //分类id
      id: 0,
      tableData: [],
      tableData1: [],
      //tab标签
      dynamicTags: [],
      // //控制input隐藏显示
      // inputVisible: false,
      // //input框输入的内容
      // inputValue: "",
      // 添加对话的
      dialogVisible: false,
      numberValidateForm: {
        attr_name: "",
      },
      //修改对话框
      exitArgument: false,
      exitValidateForm: {
        attr_name: "",
      },
      row: {},
    };
  },
  methods: {
    showInput(row) {
      console.log(row);
      row.inputVisible = true;
      console.log(111);
    },
    handleInputConfirm(row) {
      row.inputVisible = false;
    },
    //删除商品参数
    async removeId(id) {
      const res = await this.axios.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.data.meta.status != 200) return this.$message.error("删除失败！");
      this.$message({
        type: "success",
        message: "删除成功！",
        center: true,
      });
      this.handleChange();
    },
    //修改对话的确定
    exitManyArgument() {
      this.exitArgument = false;
      this.$refs["numberValidateForm"].validate(async (val) => {
        if (!val) return;
        const res = await this.axios.put(
          `categories/${this.cateId}/attributes/${this.row.attr_id}`,
          {
            attr_name: this.exitValidateForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        console.log(res);
        if (res.data.meta.status != 200) {
          return this.$message.error("修改失败！");
        }
        this.$message({
          type: "success",
          message: "修改成功！",
          center: true,
        });
        this.handleChange();
      });
    },
    //清空修改后的值
    exitDialog() {
      this.$refs["numberValidateForm"].resetFields();
    },
    //点击按钮显示修改对话框
    showExid(row) {
      this.exitArgument = true;
      this.exitValidateForm.attr_name = row.attr_name;
      this.row = row;
    },

    //点击动态参数添加分类名称
    addManyArgument() {
      this.$refs["numberValidateForm"].validate(async (val) => {
        console.log(val);
        if (!val) {
          return;
        }
        let res = await this.axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.numberValidateForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        console.log(res);
        if (res.data.meta.status == 201) {
          this.$message({
            type: "success",
            message: "添加分类成功！",
            center: true,
          });
          this.dialogVisible = false;
          if (this.activeName == "many") {
            await this.getMany();
            this.tableData = this.sMany;
          } else {
            await this.getOnly();
            this.tableData1 = this.sOnly;
          }
        } else {
          this.$message({
            type: "error",
            message: "添加分类失败！",
            center: true,
          });
        }
        console.log(res);
      });
    },
    //tab标签
    handleClose(tag) {
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    //级联触发
    async handleChange() {
      // console.log(this.value[2]);
      if (this.value.length !== 3) {
        this.value = [];
        return;
      }
      await this.getOnly();
      await this.getMany();
      this.tableData = this.sMany;
      this.tableData1 = this.sOnly;
    },
    //tabs切换触发
    async handleClick(val) {
      await this.handleChange();
      this.tableData = this.sMany;
      this.tableData1 = this.sOnly;
      // console.log(this.tableData, this.tableData1);
    },
    //同时请求many和olny参数
    async getMany() {
      let res = await this.axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          //动态参数
          sel: this.activeName,
        },
      });
      if (res.data.meta.status != 200) {
        return this.$message.error("获取参数失败！");
      }
      this.sMany = res.data.data;
      console.log(res);
      res.data.data.forEach((element) => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(" ")
          : [];
        (element.inputVisible = false), (element.inputValue = "");
      });
      console.log(res.data.data);
    },
    async getOnly() {
      let res = await this.axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          //静态参数
          sel: ["only"],
        },
      });
      this.sOnly = res.data.data;
      if (res.data.meta.status != 200) {
        return this.$message.error("获取参数失败！");
      }
      res.data.data.forEach((element) => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(" ")
          : [];
        (element.inputVisible = false), (element.inputValue = "");
      });
    },
    addDialog() {
      this.$refs["numberValidateForm"].resetFields();
    },
    //请求数据
    async getList() {
      let res = await this.axios.get("categories");
      if (res.data.meta.status == 200) {
        this.options = res.data.data;
      }
    },
  },
  mounted() {
    this.getList();
  },
  computed: {
    // 按钮是否显示
    isBtn() {
      if (this.value.length !== 3) {
        return true;
      }
      return false;
    },
    // 选中的三级分类ID
    cateId() {
      if (this.value.length === 3) {
        return this.value[2];
      }
      return null;
    },
    dialogText() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style lang='less' scope>
div {
  .box-card {
    margin-top: 15px;
    .el-form {
      margin-top: 15px;
      .el-cascader {
        width: 300px;
      }
    }
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }
}
</style>